﻿using System;
using System.Data;
using System.IO;
using System.Linq;

namespace Vcm
{
    public static class DataImport
    {
        public static DataTable ImportCsv(string filename, char delimiter, bool hasHeaderLine = true, bool clearErrataSymbols = true)
        {
            if (!File.Exists(filename))
                throw new FileNotFoundException("Couldn't find file:" + filename);
            var csvDataTable = new DataTable();
            using (var readFile = new StreamReader(filename, System.Text.Encoding.Default))
            {
                var rowItems = GetRowItems(readFile, delimiter, clearErrataSymbols);
                for (int i = 0; i < rowItems.Length; i++)
                    csvDataTable.Columns.Add(new DataColumn((rowItems[i]), typeof(string)));

                while ((rowItems = GetRowItems(readFile, delimiter, clearErrataSymbols)) != null)
                {
                    var csvDataRow = csvDataTable.NewRow();
                    csvDataRow.ItemArray = rowItems;
                    csvDataTable.Rows.Add(csvDataRow);
                }
            }
            return csvDataTable;
        }

        public static string[] GetRowItems(StreamReader readFile, char delimiter, bool clearErrataSymbols)
        {
            string line;
            if ((line = readFile.ReadLine()) == null)
                return null;

            while (line.Count(c => c == '"') % 2 == 1)
                line += "\n" + readFile.ReadLine();

            if (clearErrataSymbols)
                line = line.Replace("{", "").Replace("}", "");

            return SplittedStringHelper.RegroupItems(line.Split(delimiter), delimiter);
        }

        public static Version GetVersion()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
        }
    }
}